﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Layui.Framework.Controllers.Admin;
using Layui.Framework.Menu;
using Layui.Services.SysUser;
using Layui.Entities;
using Layui.Framework.Datatable;
using Layui.Core.Librs;
using Layui.Framework.Filters;
using Layui.Services.SysRole;
using Layui.Mvc.Areas.Admin.Models;
using Layui.Services.SysUserRole;
using Layui.Framework.Infrastructure;

namespace Layui.Mvc.Areas.Admin.Controllers
{
    [Route("admin/users")]
    public class UserController : AdminPermissionController
    {
        private ISysUserService _sysUserService;
        private ISysRoleService _sysRoleService;
        private ISysUserRoleService _sysUserRoleService;
        private IWorkContext _workContext;

        public UserController(ISysUserService sysUserService,
            ISysRoleService sysRoleService,
            IWorkContext workContext,
            ISysUserRoleService sysUserRoleService)
        {
            this._workContext = workContext;
            this._sysUserRoleService = sysUserRoleService;
            this._sysRoleService = sysRoleService;
            this._sysUserService = sysUserService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Route("", Name = "userIndex")]
        public IActionResult UserIndex(SysUserSearchArg arg, int page = 1, int size = 20)
        {
            var pageList = _sysUserService.SearchUser(arg, page, size);
            var dataSource = pageList.ToDataSourceResult(arg);
            return View(dataSource);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("edit", Name = "editUser")]
        public IActionResult EditUser(Guid? id)
        {
            if (id != null)
            {
                var model = _sysUserService.GetById(id.Value);
                if (model == null)
                    return Redirect(ViewBag.ReturnUrl);
                return PartialView(model);
            }
            return PartialView();
        }
        [HttpPost]
        [Route("edit")]
        public IActionResult EditUser(Entities.SysUser model, string returnUrl = null)
        {
            ModelState.Remove("Id");
            ViewBag.ReturnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.RouteUrl("userIndex");
            if (!ModelState.IsValid)
                return View(model);
            if (!String.IsNullOrEmpty(model.MobilePhone))
                model.MobilePhone = StringUitls.toDBC(model.MobilePhone);
            model.Name = model.Name.Trim();
            (bool Status, string Message) result;
            if (model.Id == Guid.Empty)
            {
                model.Id = Guid.NewGuid();
                model.CreationTime = DateTime.Now;
                model.Salt = EncryptorHelper.CreateSaltKey();
                model.Account = StringUitls.toDBC(model.Account.Trim());
                model.Enabled = true;
                model.IsAdmin = false;
                model.Password = EncryptorHelper.GetMD5(model.Account + model.Salt);
                model.Creator = _workContext.CurrentUser.Id;
                result = _sysUserService.InsertSysUser(model);
            }
            else
            {
                model.ModifiedTime = DateTime.Now;
                model.Modifier = _workContext.CurrentUser.Id;
                result = _sysUserService.UpdateSysUser(model);
            }
            AjaxData.Status = result.Status;
            AjaxData.Message = result.Message;
            return Json(AjaxData);
        }

        /// <summary>
        /// 设置登录锁解锁与锁定
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enabled"></param>
        /// <returns></returns>
        [Route("loginLock", Name = "loginLock")]
        public JsonResult LoginLock(Guid id, bool loginLock)
        {
            _sysUserService.LoginLock(id, loginLock, _workContext.CurrentUser.Id);
            AjaxData.Message = "登录锁状态设置完成";
            AjaxData.Status = true;
            return Json(AjaxData);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("delete/{id}", Name = "deleteUser")]
        public JsonResult DeleteUser(Guid id)
        {
            _sysUserService.DeleteUser(id, _workContext.CurrentUser.Id);
            AjaxData.Status = true;
            AjaxData.Message = "删除完成";
            return Json(AjaxData);
        }

        /// <summary>
        /// 远程验证账号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        [Route("existAccount", Name = "remoteAccount")]
        [NotPermissionFilter]
        public JsonResult RemoteAccount(string account)
        {
            account = account.Trim();
            return Json(!_sysUserService.ExistAccount(account));
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("resetPwd/{id}", Name = "resetPassword")]
        public JsonResult ResetPassword(Guid id)
        {
            _sysUserService.ResetPassword(id, _workContext.CurrentUser.Id);
            AjaxData.Status = true;
            AjaxData.Message = "用户密码已重置为原始密码";
            return Json(AjaxData);
        }

        /// <summary>
        /// 设置用户的角色
        /// </summary>
        /// <param name="id">用户di</param>
        /// <returns></returns>
        [Route("setRoles", Name = "setUserRole")]
        public IActionResult SetUserRole(Guid id)
        {
            UserRoleViewModel model = new UserRoleViewModel();
            var user = _sysUserService.GetById(id);
            if (user == null)
                return Content("用户不存在");
            model.SysUser = user;
            model.RoleList = _sysRoleService.GetAllRoles();
            var userRoleList = _sysUserRoleService.GetAll();
            if (userRoleList != null)
                model.UserRoleList = userRoleList.Where(o => o.UserId == id).ToList();
            return PartialView(model);
        }

        [HttpPost]
        [Route("setRoles")]
        public IActionResult SetUserRole(Guid userId,List<Guid> roleIds)
        {
            _sysUserRoleService.SaveUserRole(userId, roleIds);
            AjaxData.Status = true;
            AjaxData.Message = "保存成功";
            return Ok(AjaxData);
        }

    }
}